{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**item系列魔法方法就是在执行类似字典操作的时候 ，提供到的内置函数**\n",
    "\n",
    "## 一、\\_\\_getitem__\n",
    "\n",
    "在执行 中括号查找属性时，类似于字典的查询操作，可根据参数返回自定义的值\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "code_folding": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "hello: a\n",
      "hello: name\n"
     ]
    }
   ],
   "source": [
    "class Foo:\n",
    "    def __init__(self, name, sex):\n",
    "        self.name = name\n",
    "        self.sex = sex\n",
    "\n",
    "    def __getitem__(self, item):\n",
    "        return 'hello: ' + str(item)  #自定义返回的值\n",
    "\n",
    "\n",
    "f = Foo('egg', '男')\n",
    "print(f['a'])\n",
    "print(f['name'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "正常情况下，应该返回参数所对象的正确值  的代码应该是这个样子："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "egg 18\n"
     ]
    }
   ],
   "source": [
    "class Foo:\n",
    "    def __init__(self, name, age, sex):\n",
    "        self.name = name\n",
    "        self.age = age\n",
    "        self.sex = sex\n",
    "\n",
    "    def __getitem__(self, item):\n",
    "        if hasattr(self, item):\n",
    "            return self.__dict__[item]\n",
    "\n",
    "f = Foo('egg', 18, '男')\n",
    "print(f['name'], f['age'])        "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 二、\\_\\_setitem__\n",
    "\n",
    "为类设置或者赋值，正常情况下应该是对__dict__增加属性值，（也可以设置成其他的乱七八糟的），主要是在对对象进行字典操作的时候会调用这个内置函数。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "设置字典属性 hobby:apple\n",
      "{'name': 'egg', 'sex': '男', 'hobby': 'apple'}\n"
     ]
    }
   ],
   "source": [
    "class Foo:\n",
    "    def __init__(self, name, sex):\n",
    "        self.name = name\n",
    "        self.sex = sex\n",
    "\n",
    "    def __setitem__(self, key, value):\n",
    "        print('设置字典属性 {}:{}'.format(key, value))\n",
    "        self.__dict__[key] = value  #这个应该是它的正常的作用，设置成其他的也行\n",
    "\n",
    "\n",
    "f = Foo('egg', '男')\n",
    "f['hobby'] = 'apple'  #进行字典类操作的时候会调用这个内置函数\n",
    "print(f.__dict__)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 三、\\_\\_delitem__\n",
    "\n",
    "执行字典类似的删除的操作的时候，会默认执行的内置函数（如果不想让他有它应该有的作用的时候，也可以设置成别的）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "不允许删除属性 - name\n",
      "删除属性 - sex\n",
      "{'name': 'egg', 'hobby': 'apple'}\n"
     ]
    }
   ],
   "source": [
    "class Foo:\n",
    "    def __init__(self, name, sex):\n",
    "        self.name = name\n",
    "        self.sex = sex\n",
    "\n",
    "    def __setitem__(self, key, value):\n",
    "        self.__dict__[key] = value\n",
    "\n",
    "    def __delitem__(self, key):  #字典类删除操作的时候会执行到它，这是它应该有的作用，设置成其他的也行\n",
    "        if key == 'name':\n",
    "            print('不允许删除属性 - {}'.format(key))\n",
    "        else:\n",
    "            print('删除属性 - {}'.format(key))\n",
    "#             self.__dict__.pop(key, None)\n",
    "            del self.__dict__[key]\n",
    "\n",
    "\n",
    "f = Foo('egg', '男')\n",
    "f['hobby'] = 'apple'\n",
    "del f['name']\n",
    "del f['sex']\n",
    "print(f.__dict__)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {
    "height": "calc(100% - 180px)",
    "left": "10px",
    "top": "150px",
    "width": "215.6px"
   },
   "toc_section_display": true,
   "toc_window_display": true
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
